package com.wallace.downloadserver.netty

import com.wallace.downloadserver.myconst.DefineName
import com.wallace.downloadserver.redis.RedisManager
import com.wallace.downloadserver.redis.getV
import com.wallace.downloadserver.util.myEncrypt.AESKey
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Component
import java.util.*

/**
 * @Description:
 * NettyManager
 * @author Wallace
 * @Date 2022/2/14 17:36
 */
@Component
class NettyManager {

    val log: Logger = LoggerFactory.getLogger(NettyManager::class.java)

    private var redisNettyAesKeyDB: RedisTemplate<String, Any>? = null

    @Autowired
    private fun setRedisNettyAesKeyDB(redisManager: RedisManager) {
        redisNettyAesKeyDB = redisManager.getNettyAesKeyDB()
    }

    fun initAesKey(ip: String): AESKey? {
        log.info("ip = $ip")
        var aesKey: AESKey? = null
        val keys = redisNettyAesKeyDB!!.getV(ip) as? Map<*, *>
        keys?.let {
            val decoder = Base64.getDecoder()
            try {
                val key = decoder.decode((keys[DefineName.AES_KEY] as? String)?.toByteArray())
                val iv = decoder.decode((keys[DefineName.AES_IV] as? String)?.toByteArray())
                aesKey = AESKey(key, iv)
            } catch (e: IllegalArgumentException) {
                log.warn("client[$ip] fail to start AES")
            }
        }
        return aesKey
    }

}